<template>
  <div class="task-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="600px">
      <el-form ref="taskDialogFormRef" :model="state.ruleForm" :rules="rules" size="default" label-width="100px">
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="state.ruleForm.title" placeholder="请输入任务标题" clearable></el-input>
        </el-form-item>
        <el-form-item label="分配学生" prop="user_id">
          <el-select
            v-model="state.ruleForm.user_id"
            placeholder="请选择学生"
            filterable
            clearable>
            <el-option
              v-for="item in state.users"
              :key="item.user.id"
              :label="item.user.name"
              :value="item.user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="任务描述" prop="description">
          <el-input
            v-model="state.ruleForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入任务描述"
            clearable>
          </el-input>
        </el-form-item>

        <el-form-item label="任务附件">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-exceed="handleFileExceed"
            :limit="1"
            :file-list="state.taskFileList">
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                上传任务相关的附件文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="任务类型" prop="taskTypeId">
          <el-select v-model="state.ruleForm.taskTypeId" placeholder="请选择任务类型">
            <el-option v-for="type in state.taskTypes" :key="type.id" :label="type.name" :value="type.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default" :loading="state.loading">
            {{ state.dialog.submitTxt }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="taskDialog">
import { reactive, ref, onMounted } from "vue";
import { ElMessage, genFileId, UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { createTask, updateTask, getTaskTypes } from "/@/views/task/task";

// 定义子组件向父组件传值/事件
const emit = defineEmits(["refresh"]);
const uploadRef = ref<UploadInstance>();
const taskDialogFormRef = ref();

// 表单验证规则
const rules = {
  title: [
    { required: true, message: "请输入任务标题", trigger: "blur" },
    { min: 2, max: 50, message: "标题长度在2到50个字符之间", trigger: "blur" }
  ],
  user_id: [
    { required: true, message: "请选择分配的学生", trigger: "change" }
  ],
  description: [
    { required: true, message: "请输入任务描述", trigger: "blur" },
    { min: 5, max: 500, message: "描述长度在5到500个字符之间", trigger: "blur" }
  ]
};

// 文件上传相关处理
const handleFileChange: UploadProps["onChange"] = (file) => {
  state.ruleForm.taskfile = file.raw;
  state.taskFileList = [file];
};

const handleFileExceed: UploadProps["onExceed"] = (files) => {
  uploadRef.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
  state.ruleForm.taskfile = file;
  state.taskFileList = [{ name: file.name, raw: file }];
};

// 定义变量内容
const state = reactive({
  loading: false,
  users: [],
  taskTypes: [],
  ruleForm: {
    id: "",
    user_id: "",
    title: "",
    description: "",
    taskfile: null,
    taskTypeId: ""
  },
  taskFileList: [],
  dialog: {
    isShowDialog: false,
    type: "",
    title: "",
    submitTxt: ""
  }
});

// 获取任务类型列表
onMounted(() => {
  // getTaskTypes().then((res) => {
  //   state.taskTypes = res.data;
  // });
});

// 打开弹窗
const openDialog = (type: string, row?: any, users: any,taskTypes:any) => {
  state.users = users;
  state.taskTypes = taskTypes;
  if (type === "edit" && row) {
    state.ruleForm.id = row.id;
    state.ruleForm.title = row.title;
    state.ruleForm.user_id = row.assigneeId;
    state.ruleForm.description = row.description;
    state.ruleForm.taskTypeId=row.typeId;

    if (row.taskfile) {
      // 显示已有的文件名
      const filename = row.taskfile.match(/[^/]+$/)[0];
      state.taskFileList = [{ name: filename, url: row.taskfile }];
    } else {
      state.taskFileList = [];
    }

    state.dialog.title = "编辑任务";
    state.dialog.submitTxt = "保 存";
  } else {
    // 新增任务时重置表单
    state.ruleForm = {
      id: "",
      user_id: "",
      title: "",
      description: "",
      taskfile: null,
      taskTypeId: ""
    };
    state.taskFileList = [];
    state.dialog.title = "发布新任务";
    state.dialog.submitTxt = "发 布";
  }
  state.dialog.type = type;
  state.dialog.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 提交表单
const onSubmit = () => {
  taskDialogFormRef.value.validate((valid) => {
    if (!valid) return;

    state.loading = true;
    const formData = new FormData();
    formData.append("title", state.ruleForm.title);
    formData.append("description", state.ruleForm.description);
    formData.append("user_id", state.ruleForm.user_id);
    formData.append("taskTypeId", state.ruleForm.taskTypeId);

    // 如果有文件，添加到表单数据
    if (state.ruleForm.taskfile && state.ruleForm.taskfile instanceof File) {
      formData.append("taskfile", state.ruleForm.taskfile);
    }

    if (state.dialog.type === "add") {
      // 创建新任务
      createTask(formData).then((res) => {
        if (res.success===1) {
          ElMessage.success("任务发布成功");
          closeDialog();
          emit("refresh");
        } else {
          ElMessage.error(res.message || "任务发布失败");
        }
        state.loading = false;
      }).catch((error) => {
        ElMessage.error(error.message || "任务发布失败");
        state.loading = false;
      });
    } else {
      // 更新任务
      updateTask(Number(state.ruleForm.id), formData).then((res) => {
        if (res.success === 1) {
          ElMessage.success("任务更新成功");
          closeDialog();
          emit("refresh");
        } else {
          ElMessage.error(res.message || "任务更新失败");
        }
        state.loading = false;
      }).catch((error) => {
        ElMessage.error(error.message || "任务更新失败");
        state.loading = false;
      });
    }
  });
};

// 暴露变量
defineExpose({
  openDialog
});
</script>

<style scoped lang="scss">
.task-dialog-container {
  :deep(.el-upload) {
    width: 100%;
  }

  :deep(.el-form-item__content) {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  :deep(.el-select) {
    width: 100%;
  }
}
</style>
